import { createRouter, createWebHashHistory } from "vue-router";

import adminLayout from "../view/layout/index.vue";
import Index from "../view/index.vue";
import Operation from "~/view/operation/operation.vue";
import NotFound from "~/view/404.vue";
import Login from "~/view/login/login.vue";

import Authority from "~/view/setting/authority/authority.vue";
import User from "~/view/setting/user/user.vue";
import State from "~/view/setting/state.vue";

// CMDB 相关
import Secret from "~/view/cmdb/secret/secret.vue";
import Host from "~/view/cmdb/host/host.vue";
import Webshell from "~/view/cmdb/webshell.vue";

const routes = [
  {
    path: "/",
    component: adminLayout,
    redirect: "/dashboard",
    name: "首页", // 默认路由，所有用户共享
    meta: { title: "首页" },
    children: [],
  },
  {
    path: "/login",
    component: Login,
    meta: {
      title: "登录",
    },
  },
  { path: "/:pathMatch(.*)*", name: "NotFound", component: NotFound },
];

// 动态路由  用于动态添加路由
const asyncRoutes = [
  {
    path: "/dashboard",
    component: Index,
    name: "仪表盘",
  },
  {
    path: "/kubernetes",
    component: Index,
    name: "容器管理",
  },
  {
    path: "/cluster",
    name: "集群管理",
    component: Index,
  },
  {
    path: "/deployment",
    name: "工作负载",
    component: Index,
  },
  {
    path: "/service",
    name: "服务发现",
    component: Index,
  },
  {
    path: "/node",
    name: "节点管理",
    component: Index,
  },
  {
    path: "/config",
    name: "配置中心",
    component: Index,
  },
  {
    path: "/events",
    name: "事件中心",
    component: Index,
  },
  {
    path: "/pod",
    name: "仪表盘",
    component: Index,
  },
  {
    path: "/devops",
    name: "应用发布",
    component: Index,
  },
  {
    path: "/setting",
    name: "系统设置",
    component: Index,
  },

  {
    path: "/authority",
    name: "角色管理",
    component: Authority,
  },
  {
    path: "/state",
    name: "服务器状态",
    component: State,
  },
  {
    path: "/user",
    name: "用户管理",
    component: User,
  },
  {
    path: "/operation",
    name: "操作历史",
    component: Operation,
  },
  {
    path: "/secret",
    name: "认证信息",
    component: Secret,
  },
  {
    path: "/host",
    name: "主机管理",
    component: Host,
  },
  {
    path: "/host/webshell",
    name: "网页终端",
    component: Webshell,
  },
];

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 动态添加路由的方法
export function addRouters(menus) {
  // 是否有新的路由
  let hasNewRouter = false;
  const findAndAddRoutesByMenus = (Array) => {
    Array.forEach((e) => {
      let item = asyncRoutes.find((o) => o.path == e.path);
      if (item && !router.hasRoute(e.path)) {
        hasNewRouter = true;
        console.log("添加路由", item);
        router.addRoute("首页", item);
      }
      if (e.children && e.children.length > 0) {
        findAndAddRoutesByMenus(e.children);
      }
    });
  };
  findAndAddRoutesByMenus(menus);
  return hasNewRouter;
}
